package com.ye.service;

import com.ye.dao.AppCategoryDao;
import com.ye.entity.AppCategory;
import com.ye.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryService {
    @Autowired
    AppCategoryDao appCategoryDao;

    public CategoryVo tree() {
        List<CategoryVo> voList = new ArrayList<>();
        CategoryVo tree = new CategoryVo();

        //1.查询所有分类信息
        List<AppCategory> list = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory category : list) {
            CategoryVo vo = new CategoryVo();
            BeanUtils.copyProperties(category, vo);
            voList.add(vo);
        }
        for (CategoryVo vo : voList) {
            if (vo.getParentid() == null) {//这就是根节点
                tree = findChildren(vo, voList);
                break;
            }
        }
        return tree;
    }

    private CategoryVo findChildren(CategoryVo vo, List<CategoryVo> voList) {
        vo.setList(new ArrayList<>());
        for (CategoryVo categoryVo : voList) {
            if (vo.getId()==categoryVo.getParentid()){
                vo.getList().add(categoryVo);
                findChildren(categoryVo,voList);
            }
        }
        return vo;
    }
}
